"""层弹出管理 Template Router"""
from datetime import datetime, timedelta
from typing_extensions import Annotated
from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import RedirectResponse

from sqlalchemy import select

from core.database import db_session
from core.exception import AlertException
from core.formclass import NewwinForm
from core.models import NewWin
from core.template import AdminTemplates
from lib.dependency.dependencies import validate_token
from service.newwin_service import NewWinService

router = APIRouter()
templates = AdminTemplates()
templates.env.globals["start_day"] = datetime.now().strftime("%Y-%m-%d 00:00:00")
templates.env.globals["after_7days"] = (
    datetime.now() + timedelta(days=7)).strftime("%Y-%m-%d 23:59:59")

NEWWIN_MENU_KEY = "100310"


def get_newwin(db: db_session, nw_id: int):
    """
    弹出信息查询依赖注入功能
    """
    newwin = db.get(NewWin, nw_id)
    if not newwin:
        raise AlertException(f"{nw_id} : 弹出窗口不存在.", 404)

    return newwin


@router.get("/newwin_list")
async def newwin_list(request: Request, db: db_session):
    """
    弹出列表
    """
    request.session["menu_key"] = NEWWIN_MENU_KEY

    newwins = db.scalars(
        select(NewWin).order_by(NewWin.nw_id.desc())
    ).all()

    context = {
        "request": request,
        "newwins": newwins,
    }
    return templates.TemplateResponse("newwin_list.html", context)


@router.get("/newwin_form")
async def newwin_form_add(request: Request):
    """
    弹出式登记表
    """
    context = {"request": request, "newwin": None}
    return templates.TemplateResponse("newwin_form.html", context)


@router.get("/newwin_form/{nw_id}")
async def newwin_form_edit(
    request: Request,
    newwin: NewWin = Depends(get_newwin)
):
    """
    弹出式校正泡沫
    """
    context = {"request": request, "newwin": newwin}
    return templates.TemplateResponse("newwin_form.html", context)


@router.post("/newwin_form_update", dependencies=[Depends(validate_token)])
async def newwin_form_update(
    db: db_session,
    service: Annotated[NewWinService, Depends(NewWinService.async_init)],
    nw_id: int = Form(None),
    form_data: NewwinForm = Depends()
):
    """
    弹出登记和校正处理
    """
    # 注册
    if not nw_id:
        newwin = NewWin(**form_data.__dict__)
        db.add(newwin)
        db.commit()
    # 校正
    else:
        newwin = get_newwin(db, nw_id)
        for field, value in form_data.__dict__.items():
            setattr(newwin, field, value)
        db.commit()

    # 删除现有缓存
    service.fetch_newwins.cache_clear()

    return RedirectResponse(url=f"/admin/newwin_form/{newwin.nw_id}", status_code=302)


@router.get("/newwin_delete/{nw_id}", dependencies=[Depends(validate_token)])
async def newwin_delete(
    db: db_session,
    service : Annotated[NewWinService, Depends(NewWinService.async_init)],
    newwin: NewWin = Depends(get_newwin)
):
    """
    删除弹出窗口
    """
    # 删除弹出窗口
    db.delete(newwin)
    db.commit()

    # 删除现有缓存
    service.fetch_newwins.cache_clear()

    return RedirectResponse(url="/admin/newwin_list", status_code=302)
